package com.zhangzhan.gulimallorder.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import com.zhangzhan.gulimallcommcon.enums.OrderStatusEnum;
import com.zhangzhan.gulimallcommcon.tos.ActiveWareUnLockTo;
import com.zhangzhan.gulimallorder.entity.OrderEntity;
import com.zhangzhan.gulimallorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Objects;

import static com.zhangzhan.gulimallcommcon.constant.orderAndWareUnLockCons.OrderCancelMqConstant.ORDER_EVENT_EXCHANGE;
import static com.zhangzhan.gulimallcommcon.constant.orderAndWareUnLockCons.OrderCancelMqConstant.ORDER_RELEASE_ORDER_QUEUE;
import static com.zhangzhan.gulimallcommcon.constant.orderAndWareUnLockCons.WareUnLockConstant.WARE_RELEASE_WARE;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/7/3 9:38
 */
@Component
@Slf4j
@RabbitListener(queues = {ORDER_RELEASE_ORDER_QUEUE})
public class OrderTimeOutListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 订单超时
     *
     * @param order
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    @Transactional
    public void orderCancel(OrderEntity order, Message message, Channel channel) throws IOException {
        log.info("订单超时，订单号：{}", order.getOrderSn());

        OrderEntity entity = orderService.getById(order.getId());
        if (!Objects.equals(entity.getStatus(), OrderStatusEnum.RECIEVED.getCode()) || !Objects.equals(entity.getStatus(), OrderStatusEnum.SENDED.getCode())) {
            //修改订单状态
            OrderEntity orderCancel = new OrderEntity();
            orderCancel.setStatus(OrderStatusEnum.CANCLED.getCode());
            orderService.update(orderCancel, Wrappers.<OrderEntity>lambdaUpdate()
                    .eq(OrderEntity::getId, entity.getId()));
        }
        //释放任务
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        //通知库存解锁
        rabbitTemplate.convertAndSend(ORDER_EVENT_EXCHANGE, WARE_RELEASE_WARE, new ActiveWareUnLockTo(entity.getOrderSn()));
    }


}
